package thread.alternate_print;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-08-02 16:16
 **/
public class AtomicIntegerDemo {

    private int threadCount;
    private AtomicInteger count = new AtomicInteger(1);
    private final int MAX = 100;

    public AtomicIntegerDemo(int threadCount) {
        this.threadCount = threadCount;
    }

    public void print(int threadIndex) {
        while (count.get() < MAX) {
            if ((count.get() - 1)% threadCount == threadIndex) {
                System.out.println(Thread.currentThread().getName() + "-" + count.getAndIncrement());
            }
            // 交出CPU使用权
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        int threadCount = 3;
        AtomicIntegerDemo printer = new AtomicIntegerDemo(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int threadIndex = i;
            new Thread(() -> printer.print(threadIndex), "t" + (i + 1)).start();
        }
    }

}
